﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Windows.Threading;

namespace PowerMon
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {

        WindowState savedstate;
        bool ifclose;
        public static DateTime starttime;
        public static String timenow;
        
        public MainWindow()
        {
            InitializeComponent();
            starttime = DateTime.Now;
            textBlock2.Text = starttime.ToShortTimeString().ToString();
            Threadtcpserver instance = new Threadtcpserver();
            LaunchTimer();
        }
        
        protected override void OnStateChanged(EventArgs e)
        {
            savedstate = WindowState;
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            if (!ifclose)
            {
                e.Cancel = true;
                Hide();
            }
        }

        protected void OnMenuItemAboutClick(object sender, EventArgs e)
        {
            new About().Show();
        }

        private void OnNotificationAreaIconDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
            {
                Open();
            }
        }

        private void OnMenuItemOpenClick(object sender, EventArgs e)
        {
            Open();
        }

        private void Open()
        {
            Show();
            WindowState = savedstate;
        }

        private void OnMenuItemExitClick(object sender, EventArgs e)
        {
            ifclose = true;
            //Close();
            System.Environment.Exit(0);
        }

        private void TimerTick(object sender, EventArgs e)
        {
            texttime.Text = (DateTime.Now - starttime).ToString("g");
            textnum.Text = Threadtcpserver.receives.ToString();
        }

        private void LaunchTimer()
        {
            // 判断是否在设计模式，是则返回，注意：如果不加这句话，正在设计界面的时候可能会报错哦！
            if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
            {
                return;
            }

            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 1);   //间隔1秒
            timer.Tick += new EventHandler(TimerTick);
            timer.Start();
        }
    }
}
